package com.tenglong.teacher.ui.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.cuotibao.zhuoxiao.basics.utils.ClassPathResource;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.ClientUserInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.utils.StringUtils;


import java.io.Serializable;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LoginUtil {
    private Context mContext;
    private String mPhone;
    private String mPassword;
    private boolean isLoading = false;
    private LoginCallback mCallback;
    private LoginT loginT;

    public LoginUtil(Context context, LoginCallback callback) {
        this.mCallback = callback;
        this.mContext = context;
    }

    public void login(String phone, String password) {
        this.mPassword = password;
        this.mPhone = phone;
        if (isLoading) {
            mCallback.showToast(mContext.getString(R.string.login_is_loading));
            return;
        }
        if (ClassPathResource.isStringEmpty(mPhone) || ClassPathResource.isStringEmpty(mPassword)) {
            skipLogin();
            return;
        }
        if (mCallback != null) {
            mCallback.showLoadingDialog();
        }
        DataState.getInstance().appExit();
        localLogin(new LoginListener() {
            @Override
            public void onSucceed() {
                List<ClientUserInfo> userInfos = DataState.getInstance().getUserInfos();
                if (userInfos != null) {
                    isLoading = false;
                    if (userInfos.size() == 1) {
                        toLogin();
                    } else {
                        if (mCallback != null) {
                            mCallback.dissLoadingDialog();
                        }
                        SharedPreferences.Editor editor = mContext.getSharedPreferences("preference", 0).edit();
                        editor.putBoolean(StringUtils.USER_LOGIN_STATE, true);
                        editor.putString(StringUtils.PHONE_KEY, mPhone);
                        editor.putString(StringUtils.PASSWORD_KEY, mPassword);
                        editor.commit();
                        skipSelectOrganization();
                    }
                }
            }

            @Override
            public void onFailed() {
                isLoading = false;
                if (mCallback != null) {
                    mCallback.dissLoadingDialog();
                }
                skipLogin();
            }
        });
    }

    private void toLogin() {
        if (loginT == null) {
            loginT = new LoginT((Activity) mContext, new LoginT.LoginTListener() {
                @Override
                public void showLoadingDialog() {
                }

                @Override
                public void dissLoadingDialog() {
                    if (mCallback != null) {
                        mCallback.dissLoadingDialog();
                    }
                }

                @Override
                public void showToast(String message) {
                    if (mCallback != null) {
                        mCallback.showToast(message);
                    }
                }

                @Override
                public void loginSucceed() {
                    isLoading = false;
                    SharedPreferences.Editor editor = mContext.getSharedPreferences("preference", 0).edit();
                    editor.putBoolean(StringUtils.USER_LOGIN_STATE, true);
                    editor.putString(StringUtils.PHONE_KEY, mPhone);
                    editor.putString(StringUtils.PASSWORD_KEY, mPassword);
                    editor.commit();
                    skipHome();
                }

                @Override
                public void loginFailed() {
                    isLoading = false;
                    DataState.getInstance().appExit();
                }
            });
        }
        loginT.getUserInfos();
    }

    private void localLogin(final LoginListener loginListener) {
        final ClientUserInfo userInfo = new ClientUserInfo();
        userInfo.setPhone(mPhone);
        userInfo.setPassword(mPassword);
        CreateRequestEntity.getWebServiceLogin().login(userInfo).enqueue(new Callback<BaseResult<List<ClientUserInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<ClientUserInfo>>> call, Response<BaseResult<List<ClientUserInfo>>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    if (response.body().data != null && response.body().data.size() > 0) {
                        DataState.getInstance().appLogin(response.body().data);
                        loginListener.onSucceed();
                    } else {
                        loginListener.onFailed();
                        if (mCallback != null) {
                            mCallback.showToast("返回参数错误");
                        }
                    }
                } else {
                    loginListener.onFailed();
                    if (mCallback != null) {
                        mCallback.showToast(ResultVerifier.serceErrers(response));
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseResult<List<ClientUserInfo>>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                loginListener.onFailed();
            }
        });
    }

    private void skipLogin() {
        if (mContext instanceof LoginActivity) return;
        Intent intent = new Intent("com.tenglong.LoginActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mContext.startActivity(intent);
    }

    private void skipHome() {
        Intent intent = new Intent("android.intent.action.home");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mContext.startActivity(intent);
        ((Activity) mContext).finish();
    }

    private void skipSelectOrganization() {
        Intent intent = new Intent();
        intent.setClass(mContext, LoginSelectOrganizationActivity.class);
        intent.putExtra(LoginSelectOrganizationActivity.KEY_SWITCH_ORGANIZATION_TYPE,LoginSelectOrganizationActivity.TYPE_LOGIN_SWITCH_ORGANIZATION);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mContext.startActivity(intent);
    }


    public interface LoginListener {
        void onSucceed();

        void onFailed();
    }


    public interface LoginCallback {
        void showLoadingDialog();

        void dissLoadingDialog();

        void showToast(String message);
    }
}
